#! /usr/bin/env python
# -*- coding: utf8 -*-
#
#  gitlab irc sender
#  Copyright (C) 2016-2017  Andrei Karas (4144)
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging

from code.apihandler import ApiHandler
from code.configuration import Configuration
from code.core import Core
from code.messagehandler import MessageHandler
from code.serverhandler import ServerHandler

try:
    from SocketServer import ThreadingMixIn
except ImportError:
    from socketserver import ThreadingMixIn

try:
    from BaseHTTPServer import HTTPServer
except ImportError:
    from http.server import HTTPServer

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

class MainClass:
    @staticmethod
    def init_config(name):
        Core.config = Configuration()
        Core.config.loadConfiguration(name)

    @staticmethod
    def init_messages():
        Core.messageHandler = MessageHandler()
        Core.messageHandler.start()

    @staticmethod
    def init_api():
        Core.apiHandler = ApiHandler()
        Core.apiHandler.start()

    @staticmethod
    def init_log():
        Core.log = logging.getLogger('log')
        Core.log.setLevel(Configuration.log_level)
        log_handler = logging.handlers.RotatingFileHandler(
            Configuration.log_file,
            maxBytes = Configuration.log_max_size,
            backupCount = 10)
        f = logging.Formatter("%(asctime)s %(message)s",
            "%B %d %H:%M:%S")
        log_handler.setFormatter(f)
        Core.log.addHandler(log_handler)

    @staticmethod
    def run_server():
        try:
            # single threaded
            # Core.server = HTTPServer((Core.config.global_options.listen_host, Core.config.global_options.listen_port), ServerHandler)
            # milti threaded
            Core.server = ThreadedHTTPServer((Core.config.global_options.listen_host, Core.config.global_options.listen_port), ServerHandler)
            Core.server.timeout = 5
            print('Started http server on {0}:{1}'.format(Core.config.global_options.listen_host, Core.config.global_options.listen_port))
            Core.server.serve_forever()
        except KeyboardInterrupt:
            print('^C received, shutting down the web server')
            Core.apiHandler.die = True
            Core.messageHandler.die = True
            Core.server.socket.close()
            Core.messageHandler.join()

if __name__ == '__main__':
    MainClass.init_log()
    MainClass.init_config("config.yaml")
    MainClass.init_messages()
    MainClass.init_api()
    MainClass.run_server()
